﻿Imports System.IO
Imports System.Reflection

Module MainModul

    ''' <summary>
    ''' for logging use log4net-framework
    ''' configured by extra file SimplyBackup.exe.log4net.xml
    ''' </summary>
    ''' <remarks></remarks>
    Public log As log4net.ILog

    ''' <summary>
    ''' Aufgabe: Ziel ist es, die Daten von einem NetzwerkOrdner auf einer externen Karte (BACKUP_ZEIT) zu sichern.
    ''' info: error 5 (processID not found) will be ignored.
    ''' 
    ''' backupFolder:
    ''' - Verzeichnis, in dem das Backup ertsellt werden soll, Beispiel: test\backup dann sieht der destinationFolder aus: d:\test\backup
    ''' - wenn der backupFolder leer ist, dann wird er ignoriert
    ''' 
    ''' History:
    ''' since 25.07.2013: 
    '''   - adding 3. and 4.parameter
    '''   - adding log4net
    '''   - reading assemblyfileversion
    ''' since 28.05.2013 initial
    ''' 
    ''' www-info for log4net: 
    '''    http://logging.apache.org/log4net/download.html
    '''    step-by step introduction: http://www.codeproject.com/Articles/42276/How-to-Use-Log4Net-with-VB-NET-A-Simple-Step-By-St
    '''    log4net ConfigFile:="SimplyBackup.exe.log4net.xml" (configured in AssemblyInfo.vb)
    ''' </summary>
    ''' <param name="cmdArgs">
    ''' String-Command-Array:
    ''' 1.Param: backupDriveName (BACKUP_ZEIT) Laufwerk, wohin archiviert werden soll
    ''' 2.Param: sourceFolder (Z:\zeiten) Dateien, die archiviert werden sollen
    ''' [3.Param: quiteMode (true: es wird keine messagebox ausgegeben)]
    ''' [4.Param: backupFolder (folder for copying the backup-datas)] example: test\backup
    ''' </param>
    ''' <returns>on error -1 otherwise 0</returns>
    ''' <remarks></remarks>
    Function Main(ByVal cmdArgs() As String) As Integer
        On Error GoTo myError
        Dim backupDriveName As String, finderBackupDrive As Boolean, backupDrive As System.IO.DriveInfo
        Dim sourceFolder As String, finderUSBDrive As Boolean, sourceDrive As System.IO.DriveInfo
        Dim returnValue As Integer = 0
        Dim prefixBackupFolderName As String = "backup" 'backup sub folder
        Dim myBackupLogfile As String = "simplybackup.log"
        Dim myTxt As String = "" 'text for message box or logging
        Dim oneDir As DirectoryInfo, destinationDirectoryName As String
        Dim newProc As Diagnostics.Process, myTime As Date, myTimeStr As String, isQuideMode As Boolean
        Dim backupFolder As String '4.Param  , example: test\backup

        '0.1 Activate the logging: Get the logger as named in the configuration file:
        log = log4net.LogManager.GetLogger("Log4NetSimplyBackup")
        log.Info("Main(): starte Backup on:" & Now)

        '0.1 get the assemblyfileversion and title:
        Dim msgboxTitel As String = HelperModul.getAssemblyInfos
        log.Debug("Main(): myBackupLogfile=" & myBackupLogfile)

        '0.2 initial settings:
        finderBackupDrive = False
        finderUSBDrive = False
        sourceDrive = Nothing
        backupDrive = Nothing

        '1. check first the first and second arguments:
        If HelperModul.checkArgs(cmdArgs, 2) = False Then
            log.Debug("Main(): missing arguments! stopping here!")
            MsgBox("Fehler: falsche Anzahl an Parameter! Es müssen 2 Parameter angegeben werden:" & vbNewLine & _
                    "1.Parameter: backupDriveName (BACKUP_ZEIT), Laufwerk, wohin archiviert werden soll" & vbNewLine & _
                    "2.Parameter: sourceFolder (Z:\zeiten), Dateien, die archiviert werden sollen", MsgBoxStyle.Critical, msgboxTitel)
            GoTo myExit
        End If
        backupDriveName = cmdArgs(0)
        sourceFolder = cmdArgs(1)
        log.Debug("Main(): backupDriveName=" & backupDriveName)
        log.Debug("Main(): sourceFolder=" & sourceFolder)

        '2. get the 3.Param: isQuideMode
        If cmdArgs.Length > 2 Then
            isQuideMode = CBool(cmdArgs(2))
        Else
            isQuideMode = False
        End If
        log.Debug("Main(): isQuideMode=" & isQuideMode)

        '3. get the 4.Param: backupFolder
        If cmdArgs.Length > 3 Then
            backupFolder = CStr(cmdArgs(3)).Trim()
        Else
            backupFolder = ""
        End If
        log.Debug("Main(): backupFolder=" & backupFolder)

        If isQuideMode = False Then
            myTxt = "1. backupDriveName=" & backupDriveName & vbNewLine & _
                "2. sourceFolder=" & sourceFolder & vbNewLine & _
                "3. quideMode=" & isQuideMode & vbNewLine & _
                "4. backupFolder=" & backupFolder
            If MsgBox("xcopy-Backup wird gestartet mit folgenden Parametern:" & vbNewLine & myTxt, MsgBoxStyle.OkCancel, msgboxTitel) = MsgBoxResult.Cancel Then
                log.Info("user cancels the backup-process!")
                GoTo myExit
            End If
        End If

        '4. find the BackupDrive:
        Dim myCol = HelperModul.finderBackupDrive(backupDriveName)
        'wenn das backup drive nicht gefunden wurde, dann stoppe hier
        If myCol.Item(1) = False Then
            MsgBox("Backup-Drive '" & backupDriveName & "' nicht gefunden!" & vbNewLine & "Bitte externe Festplatte/USB-Stick/SDCARD anschliessen!", MsgBoxStyle.Critical, msgboxTitel)
            GoTo myExit
        End If
        backupDrive = myCol.Item(2)

        '5. create the destination-backup-folder:
        destinationDirectoryName = backupDrive.RootDirectory.FullName
        If Len(backupFolder) > 0 Then
            destinationDirectoryName = destinationDirectoryName & backupFolder
        End If
        log.Debug("Main(): destinationDirectoryName=" & destinationDirectoryName)

        '6. starte das eigentliche Backup per xcopy-befehl:
        Dim isCopied As Boolean = HelperModul.makeCopy(sourceFolder, destinationDirectoryName, myBackupLogfile)
        If isCopied = False Then
            log.Error("Main(): Fehler beim Kopieren der Daten!")
            MsgBox("Fehler beim Kopieren der Daten!", MsgBoxStyle.Critical, msgboxTitel)
            GoTo myExit
        End If

        '7. successfully end:
        If isQuideMode = False Then
            MsgBox("Das Backup ist erfolgreich beendet, siehe Logfile:" & myBackupLogfile, MsgBoxStyle.Information, msgboxTitel)
        End If
myExit:
        log.Info("Main(): " & msgboxTitel & " ...ending-time:" & Now & " returnValue=" & returnValue)
        Return returnValue
        Exit Function

myError:
        If Err.Number = 5 Then
            'processID not found, ignor it
            log.Debug("Main(): Fehler Err.Number=5 (processID not found) will be ignored!")
            Resume Next
        End If
        returnValue = -1
        Dim errMsg As String
        errMsg = "Main(): " & Err.Number & "::" & Err.Description
        log.Error(errMsg)
        MsgBox(errMsg, MsgBoxStyle.Critical, msgboxTitel)
        Resume myExit
    End Function

End Module
